/*
 * Wantmore - Service Delivery Platform.
 *
 * $Id: PhotoAlbumsServiceImpl.java 59 2010-10-12 08:29:50Z alexey.batyuta@gmail.com $
 *
 * Copyright 2010 by Sunbay Software Crimea Ltd.
 * All rights reserved
 */
package ua.crimea.bat.ss.services;


import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;
import org.springframework.util.FileCopyUtils;
import ua.crimea.bat.ss.dao.PhotoDao;
import ua.crimea.bat.ss.model.beans.Album;
import ua.crimea.bat.ss.model.beans.Image;

import javax.servlet.ServletOutputStream;
import java.io.IOException;
import java.util.Collection;
import java.util.List;

/**
 * User: bat
 * Date: Mar 26, 2010
 * Time: 8:09:20 AM
 */
@Service
@Component
public class PhotoAlbumsServiceImpl implements PhotoAlbumsService {
    @Autowired
    PhotoDao photoDao;

    public PhotoAlbumsServiceImpl() {
    }

    public PhotoAlbumsServiceImpl(PhotoDao photoDao) {
        setPhotoDao(photoDao);
    }

    public void setPhotoDao(PhotoDao photoDao) {
        this.photoDao = photoDao;
    }

    public PhotoDao getPhotoDao() {
        return photoDao;
    }


    public Collection<Album> findAlbums(Boolean isPublic) throws DataAccessException {
        if (isPublic) {
            return getPhotoDao().findPublicAlbums();
        } else {
            return getPhotoDao().findPrivateAlbums();
        }
    }

    public Album loadAlbum(Integer id) throws DataAccessException {
        return getPhotoDao().loadAlbum(id);
    }

    public Image loadImage(Integer id) throws DataAccessException {
        return getPhotoDao().loadImage(id);
    }

    public void storeAlbum(Album album) throws DataAccessException {
        getPhotoDao().storeAlbum(album);
    }

    public void storeImage(Image image) throws DataAccessException {
        getPhotoDao().storeImage(image);
    }

    public void deleteAlbum(Integer id) throws DataAccessException {
        getPhotoDao().deleteAlbum(id);
    }

    public void deleteImage(Integer id) throws DataAccessException {
        getPhotoDao().deleteImage(id);
    }

    public void streamThumb(Integer id, ServletOutputStream outputStream) throws IOException {
        Image image = loadImage(id);
        FileCopyUtils.copy(image.getThumb(), outputStream);
    }

    public void streamImage(Integer id, ServletOutputStream outputStream, List<Image> images) throws IOException {
        for (Image image : images) {
            if (id == image.getId()) {
                FileCopyUtils.copy(image.getImage(), outputStream);
                return;
            }
        }
    }
}
